package org.shan.db;


import com.mlnx.common.utils.MyLog;

import org.shan.db.orm.QueryRule;
import org.shan.db.orm.SqliteDaoSupport;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by amanda.shan on 2020/1/22.
 */
public class TestDb {

    MyLog log = MyLog.getLog(getClass());

    private SqliteDaoSupport sqliteDaoSupport = new SqliteDaoSupport<Company, Integer>(Company.class,
            "jdbc:sqlite:test.db");

    private void initDb() {

        String sql = " DROP TABLE IF EXISTS `Company`; " +
                "CREATE TABLE TestData  (" +
                " `ID` INTEGER PRIMARY KEY AUTOINCREMENT," +
                "`ADDRESS` VARCHAR(500) DEFAULT NULL," +
                " `AGE` INT DEFAULT NULL," +
                " `TIME` BIGINT DEFAULT NULL" +
                " );" +
                "CREATE INDEX idx_time ON Company (TIME);";

        try {
            sqliteDaoSupport.createTable(sql);
        } catch (SQLException e) {
            log.error(e, "数据库初始化失败");
        }
    }

    public void testSelect() {
        try {
            QueryRule queryRule = QueryRule.getInstance()
                    .andEqual("age", 11);
            List list = sqliteDaoSupport.select(queryRule);
            System.out.println(list);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void testInsert() {

        List<Company> companies = new ArrayList<>();
        for (int i = 1; i < 10; i++) {
            Company company = new Company();
            company.setId(i);
            company.setTime(System.currentTimeMillis() + i * 1000);
            company.setAge(11);
            company.setBytes(new byte[1000]);
            company.setAddress("浙江宁波");
            companies.add(company);
        }

        try {
            sqliteDaoSupport.insertBatch(companies);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void testCount() {

        long count = 0;
        try {
            count = sqliteDaoSupport.getCount(QueryRule.getInstance());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(count);
    }

    public void testDelete() {
        try {
            QueryRule queryRule = QueryRule.getInstance();
//                    .andEqual("id", 1);
            int delete = sqliteDaoSupport.delete(queryRule);
            System.out.println(delete);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        TestDb testDb = new TestDb();

        testDb.testInsert();

//        testDb.testSelect();
//        testDb.testCount();

//        testDb.testDelete();
    }
}
